<template>
  <div>
    <Navbar :appTitle="appTitle" />
    <div
      class="form-content wrap-apply"
      :style="{
        top: GLOBAL.currentEnvironment ? '0' : '',
        height: GLOBAL.currentEnvironment ? '100vh' : 'calc(100vh - 100px)',
        paddingBottom: GLOBAL.currentEnvironment ? '120px' : '',
      }"
    >
      <van-cell-group class="formItemFlex">
        <p class="label required FormTit"><span></span>入库任务编号</p>
        <div class="haveUnitBox">
          <van-field
            v-model="buildForm.taskCode"
            :maxLength="50"
            placeholder="请输入"
            input-align="right"
          />
        </div>
      </van-cell-group>
      <div class="bottomLine"></div>
      <van-cell-group  class="formItemFlex">
        <p class="label required FormTit"><span></span>业务类型</p>
        <van-field-select-picker
          :supportClear="true"
          label=""
          placeholder="请选择"
          v-model="buildForm.type"
          :columns="warehousingTypes"
          :option="{ label: 'text', value: 'value' }"
        />
        <div class="bottomLine"></div>
      </van-cell-group>
      <div class="bottomLine"></div>
      <van-cell-group  class="formItemFlex">
        <p class="label FormTit"><span></span>源单号</p>
        <div class="haveUnitBox">
          <van-field
            v-model="buildForm.sourceNumber"
            :maxLength="50"
            placeholder="请输入"
            input-align="right"
          />
        </div>
        <div class="bottomLine"></div>
      </van-cell-group>


      <div class="list" >
        <div class="wrap"
          v-for="(p, i) in entryDetails"
          :key="p.goodsKey"
          v-show="entryDetails.length != 0"
          style="margin-bottom: 10px;"
        >
          <van-cell-group>
            <p class="label otherText">
              <span>物品明细（{{ i + 1 }}）</span>
              <span class="deleteStyle" @click="deleteGoods(i)">删除</span>
            </p>
            <div class="bottomLine"></div>
            <div class="top">
              <div class="icon"></div>
              <div class="title titleWidth">
                {{ p.goodsCode	 }}| {{ p.goodsName }}| {{ p.spec }}
              </div>
            </div>
            <div class="center">
              <div>
                <p>
                  <span class="key">产地：</span>
                  <span class="value">{{ p.address	}}</span>
                </p>
                <p>
                  <span class="key">包装规格：</span>
                  <span class="value">{{ p.packageSpec	}}</span>
                </p>
                <p>
                  <span class="key">单位：</span>
                  <span class="value">{{ p.unitName	}}</span>
                </p>
              </div>
            </div>

            <van-cell-group class="formItemFlex">
              <p class="label required FormTit"><span></span>批号</p>
              <div class="haveUnitBox">
                <van-field
                  v-model="p.batchCode"
                  :maxLength="50"
                  placeholder="请输入"
                  input-align="right"
                  @input="batchCodeChange(i, p)"
                />
              </div>
            </van-cell-group>
            <div class="bottomLine"></div>
            <van-cell-group class="formItemFlex">
              <p class="label required FormTit"><span></span>生产日期</p>
              <div class="haveUnitBox">
                <van-field
                  input-align="right"
                  is-link
                  readonly
                  name="picker"
                  v-model="p.produceDate"
                  @click="openTimePicker(i, p.produceDate)"
                  placeholder="请选择"
                />
              </div>
            </van-cell-group>
            <div class="bottomLine"></div>
            <van-cell-group class="formItemFlex">
              <p class="label required FormTit"><span></span>物品数量</p>
              <div class="haveUnitBox">
                <van-field
                  v-model="p.inboundGoodsNum"
                  type="number"
                  placeholder="请输入"
                  input-align="right"
                  :formatter="(e) => needInNumChange(e)"
                />
              </div>
            </van-cell-group>
          </van-cell-group>
        </div>

        <div class="addGoodScontain">
          <div class="addgoods" @click="addInventoryGoods">
            <van-icon name="plus" size="16px" color="#1890ff" style="top: 2px" />
            <a>物品</a>
          </div>
        </div>
      </div>

      <div class="search-bottoms">
        <van-button class="btnconfirm" :loading="subLoading" loading-text="提交中..." @click="btnConfirm">提交</van-button>
      </div>
    </div>
    <!--选择物品 -->
    <goods-pickers-ak
      v-if="showGoodsPicker"
      :listUrl="listUrl"
      :columns="goodsColumns"
      :selectedGoods="[]"
      @getCheckedGoods="getCheckedGoods"
    ></goods-pickers-ak>
    <!--选择生产日期 -->
    <van-popup v-model="timePickShow" position="bottom">
      <van-datetime-picker
        @confirm="confirmPick"
        v-model="happenTime"
        @cancel="cancelPick"
        type="date"
        title="生产日期"
        :formatter="formatter"
      />
    </van-popup>
  </div>
</template>
<script>
import moment from "moment";
import Navbar from "@/components/navBar/navBar_right";
import VanFieldSelectPicker from "@/components/ActionSheet/VanFieldSelectPicker";
import GoodsPickersAk from "@/components/choiceuse/GoodsPickersAk";
import {
  genEntityCode,
  getDictItemsByTypes,
  inboundTaskAdd,
  inboundTaskEdit,
  getBathRelProductDate,
  inboundTaskDetail,
  inboundTaskDetailGoodsList,
} from "@/api/inventoryOrder";
import store from "@/store";

export default {
  name: "warehousingTaskForm",
  components: {
    Navbar,
    VanFieldSelectPicker,
    GoodsPickersAk,
  },
  data() {
    return {
      appTitle: "新建入库任务",
      buildForm: {
        applyUserId: "",
        taskCode: "",
        type: "FINISHED",
        sourceNumber: "",
      },
      showGoodsPicker: false,
      listUrl: "/baseSetting/wmsGoods/queryByPage",
      goodsColumns: {
        titleKey: ['goodsCode', 'goodsName', 'spec'], //标题
        content: [
          //内容
          {
            name: "产地",
            key: ["address"],
          },
          {
            name: "包装规格",
            key: ["packageSpec"],
          },
          {
            name: "单位",
            key: ["unitIdText"],
          },
        ],
        operationText: "",
      },
      entryDetails:[],
      recentGoodsIndex: '',
      warehousingTypes: [],
      timePickShow: false,
      happenTime: '',
      isEdit: false,
      subLoading: false
    };
  },
  beforeRouteLeave(to, from, next) {
    if (this.showGoodsPicker) {
      this.showGoodsPicker = false;
      if(this.isEdit) {
        this.appTitle = '编辑入库任务';
      }else {
        this.appTitle = '新建入库任务';
      }
      next(false);
    } else {
      next();
    }
  },
  async created() {
    store.commit("SET_CURRENT_PREFIX", "/jksaas-produce/produce");
    this.initData();
  },
  methods: {
    // 重置form表单
    resetForm () {
      this.buildForm = {
        applyUserId: "",
        taskCode: "",
        type: "FINISHED",
        sourceNumber: "",
      }
      this.entryDetails = []
      this.recentGoodsIndex = ''
      this.warehousingTypes = []
      this.happenTime = ''
    },
    // 提交
    btnConfirm() {
      if (!this.buildForm.taskCode) {
        this.$toast(`请输入入库任务编号`);
        return;
      }

      if (!this.buildForm.type) {
        this.$toast(`请选择业务类型`);
        return;
      }

      let isValidated = true;
      try {
        // 入库物品明细 为空 选项名称、数量 表单验证
        if (this.entryDetails && this.entryDetails.length > 0) {
          this.entryDetails.forEach((element, index) => {
            if (element.goodsId) {
              if (!element.batchCode || element.batchCode == "") {
                isValidated = false;
                throw new Error(`物品明细（${index + 1}）批号不可为空`);
              }
              if (!element.produceDate || element.produceDate == "") {
                isValidated = false;
                throw new Error(`物品明细（${index + 1}）生产日期不可为空`);
              }
              if (!element.inboundGoodsNum || element.inboundGoodsNum == "" || element.inboundGoodsNum == 0) {
                isValidated = false;
                throw new Error(`物品明细（${index + 1}）物品数量不可为空且不为零`);
              }
            } else {
              isValidated = false;
              throw new Error(`请选择物品`);
            }
          });

          let duplicateindex = this.hasDuplicateObjects(this.entryDetails)
          if(duplicateindex != -1) {
            throw new Error(`物品（${this.entryDetails[duplicateindex]['goodsName']}）批号不可相同`);
          }
        } else {
          isValidated = false;
          throw new Error(`请选择物品`);
        }

        if (!isValidated) {
          return;
        }
      } catch (error) {
        this.$toast(error.message);
        return false;
      }
      this.handleSubmit();
    },
    handleSubmit() {
      let params = {
        ...this.buildForm,
        goodsList: this.entryDetails.map((ele) => {
          return {
            id: this.isEdit ? ele.id : '',
            goodsId: ele.goodsId,
            batchCode: ele.batchCode,
            goodsBatchId: ele.goodsBatchId,
            produceDate: ele.produceDate,
            inboundGoodsNum: ele.inboundGoodsNum,
          };
        }),
      };

      let commitApi = "";
      let successMeg = "";
      if (this.isEdit) {
        commitApi = inboundTaskEdit;
        successMeg = "入库任务编辑成功！";
      } else {
        commitApi = inboundTaskAdd;
        successMeg = "入库任务创建成功！";
      }
      this.subLoading = true
      commitApi(params).then((res) => {
        if (res.success) {
          this.$toast(successMeg);
          this.initData()
        } else {
          this.$toast(res.message);
        }
        this.subLoading = false
      }).catch(() => {
        this.subLoading = false
      }).finally(() => {
        this.subLoading = false
      })
    },
    // 初始化页面数据
    initData() {
      let id = this.$route.query.id;

      // 获取当前用户 设定为提交人参数
      let currentLoginUser = JSON.parse(localStorage.getItem("pro__Login_Userinfo")).value;

      this.resetForm()
      // 获取入库任务类型
      getDictItemsByTypes({type: 3}).then((res) => {
        if (res.code == 200 && res.result) {
          this.warehousingTypes = res.result
        }
      });

      if(id) {
        this.isEdit = true
        this.appTitle = "编辑入库任务";
        // 入库任务详情 基本信息
        inboundTaskDetail({taskId: id}).then((res) => {
          if (res.code == 200 && res.result) {
            let {id, taskCode, type, sourceNumber} = res.result;
            this.buildForm = {
              id: id || '',
              sourceNumber: sourceNumber || '',
              taskCode: taskCode || '',
              type: type || '',
              applyUserId: currentLoginUser.id
            }
          } else {
            this.$toast(res.message);
          }
        });
        // 入库任务详情 物品明细
        inboundTaskDetailGoodsList({taskId: id}).then((res) => {
          if (res.code == 200 && res.result) {
            this.getCheckedGoods(res.result.records)
          } else {
            this.$toast(res.message);
          }
        });
      }else {
        this.isEdit = false
        this.appTitle = "新建入库任务";
        this.buildForm.applyUserId = currentLoginUser.id;
        // 生产入库任务编号
        genEntityCode({ entityCode: "WMS_INBOUND_TASK",}).then((res) => {
          if (res.code == 200) {
            this.buildForm.taskCode = res.result;
          } else {
            this.buildForm.taskCode = "";
            this.$toast(res.message);
          }
        });
      }
    },
    // 入库物品明细-》添加
    addInventoryGoods() {
      this.appTitle = "选择物品";
      this.showGoodsPicker = true;
    },
    // 入库物品明细-》删除
    deleteGoods(i) {
      this.entryDetails.splice(i, 1);
    },
    // 确认选中物品 物品可复选
    async getCheckedGoods(list) {
      this.showGoodsPicker = false;
      this.appTitle = this.isEdit ? "编辑入库任务" : "新建入库任务";
      let recTime = moment(new Date()).format("YYYY-MM-DD");
      let newbatchCode = recTime.replace(/\-/g,"").substring(2)

      let checkedGoods = list.map((son) => {
        let { id, goodsId, goodsCode, goodsName, spec, address, packageSpec, unitIdText, unitName, batchCode, goodsBatchId, produceDate, inboundGoodsNum } = son

        if(!goodsId) {
          goodsId = id
          id = ''
        }
        if(!unitName) {
          unitName = unitIdText
        }

        return {
          id: id || '',
          goodsKey: goodsId + '_' + Math.floor(Math.random() * 1000),
          goodsId: goodsId || '',
          goodsCode: goodsCode || '-',
          goodsName: goodsName || '-',
          spec: spec || '-',
          address: address || '-',
          packageSpec: packageSpec || '-',
          unitName: unitName || '-',
          batchCode: batchCode || newbatchCode,
          goodsBatchId: id || '',
          produceDate: produceDate || recTime,
          inboundGoodsNum: inboundGoodsNum || ''
        };
      });

      this.entryDetails = this.entryDetails.concat(checkedGoods)

      this.entryDetails.forEach((ele) => {
        let {goodsId, batchCode} = ele
        getBathRelProductDate({goodsId, batchCode}).then((res) => {
          if(res.code == 200 && res.result) {
            ele.goodsBatchId = res.result.id
          }else {
            ele.goodsBatchId = ''
          }
        }).catch(()=>{
          ele.goodsBatchId = ''
        })
      })
    },
    // 入库单 物品明细 数量处理
    needInNumChange(e) {
      let value = this.clearNoNum(e);
      return value;
    },
    /*数量处理*/
    clearNoNum(value) {
      //先把非数字的都替换掉，除了数字和.
      value = value.replace(/[^\d.]/g, "");
      //保证只有出现一个.而没有多个.
      value = value.replace(/\.{2,}/g, ".");
      //必须保证第一个为数字而不是.
      value = value.replace(/^\./g, "");
      //保证.只出现一次，而不能出现两次以上
      value = value
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      //只能输入四个小数
      value = value.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, "$1$2.$3");
      // console.log(value.includes('.'),'wwwwww')
      //小数位处理
      if (value.substring(0, 1) == "0" && value.substring(0, 2) != "0.") {
        value = "0";
      }
      //输入长度控制
      if (value > 99999999999999.9999) {
        value = '';
      }

      return value;
    },
    // 打开选择时间
    openTimePicker(index, value) {
      this.recentGoodsIndex = index
      if(this.entryDetails[this.recentGoodsIndex]['goodsBatchId']) {
        // 当前批号已存在 生产日期禁止变动
        return
      }

      if(value) {
        this.happenTime = new Date(value)
      }else {
        this.happenTime = ''
      }

      this.timePickShow = true
    },
    // 确定选择时间
    confirmPick(date) {
      this.entryDetails[this.recentGoodsIndex].produceDate = moment(date).format("YYYY-MM-DD");
      this.timePickShow = false;
    },
    // 取消选择时间
    cancelPick() {
      this.timePickShow = false;
    },
    formatter(type, val) {
      if (type === "year") {
        return val + "年";
      }
      if (type === "month") {
        return val + "月";
      }
      if (type === "day") {
        return val + "日";
      }
      return val;
    },
    // 批号变更查询
    batchCodeChange(index, item) {
      let {goodsId, batchCode} = item
      if(goodsId && batchCode) {
        getBathRelProductDate({goodsId, batchCode}).then((res) => {
          if(res.code == 200 && res.result) {
            this.entryDetails[index].produceDate = res.result.produceDate
            this.entryDetails[index].goodsBatchId = res.result.id
          }else {
            this.entryDetails[index].produceDate =  moment(new Date()).format("YYYY-MM-DD"),
            this.entryDetails[index].goodsBatchId = ''
          }
        })
      }
    },
    // 验证数组内是否存在相同对象
    hasDuplicateObjects(arr) {
      for (let i = 0; i < arr.length - 1; i++) {
        for (let j = i + 1; j < arr.length; j++) {
          if (this.isEqual(arr[i], arr[j]) > -1) {
            return this.isEqual(arr[i], arr[j]); // 存在重复对象
          }
        }
      }
      return -1; // 不存在重复对象
    },
    isEqual(obj1, obj2) {
      if(obj1['goodsId'] == obj2['goodsId']) {
        if(obj1['batchCode'] == obj2['batchCode']) {
          let recIndex = this.entryDetails.findIndex((ele) => ele.goodsId == obj1['goodsId'])
          return recIndex
        }else {
          return -1
        }
      }else {
        return -1
      }
    }
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/theme.scss";
@import "@/views/workManagement/materialRequisition/materialForm.scss";
.form-content {
  width: 100%;
  height: calc(100vh - 203px);
  background: #f5f5f5;
  overflow: scroll;
  padding: 20px 0;
  .formgroup {
    background: #ffffff;
    margin-top: 0.1rem;
    margin-bottom: 0.2rem;
    padding-top: 0.1rem;

    .title {
      width: 0.58rem;
      height: 0.14rem;
      font-size: 0.15rem;
      font-family: PingFang SC;
      font-weight: 400;
      color: #191f25;
      line-height: 0.05rem;
      margin-left: 0.16rem;
    }
  }
  .search-bottoms {
    width: 100%;
    height: 100px;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    bottom: 0px;
    padding: 0rem 11px;
    box-sizing: border-box;
    font-size: 32px;
    font-weight: 500;
    z-index: 9;
    .btnconfirm {
      flex: 1;
      background: #1890ff;
      box-sizing: border-box;
      height: 78px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 6px;
      color: #ffffff;
    }
  }
}
.bottomLine {
  height: 1px;
  background-color: #f2f2f2;
  margin: 0 2px;
}
.haveUnitBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
  padding-right: 32px;
  /deep/ .van-cell {
    padding-right: 0;
    width: 600px;
  }
  /deep/ .van-field__control {
    max-width: 700px;
    // text-align: right;
  }
}
/deep/ .van-nav-bar {
  z-index: 99;
}
/deep/.van-sidebar-item--select::before {
  color: #1890ff;
  background-color: #1890ff;
}
/deep/.van-tree-select__item--active {
  color: #1890ff;
}
.addGoodScontain {
  display: flex;
  flex-wrap: nowrap;
  .addgoods {
    flex: 1;
    background: #fff;
    font-size: 32px;
    text-align: center;
    height: 78px;
    line-height: 78px;
    color: #1890ff;
  }
}
.required span::after {
  left: -20px;
  top: 3px;
}
.filedClear {
  width: 28px;
  height: 28px;
}
.formItemFlex {
  display: flex;
  flex-direction: row;
  .FormTit {
    flex: 1;
    min-width: 3.3rem;
    padding-top: 0.33rem;
  }
  .haveUnitBox {
    flex: 1;
    .van-cell {
      width: 6.2rem;
    }
  }
}
.list {
  margin-top: 10px;
  .wrap {
    background: #fff;
    margin-top: 20px;
    width: 100vw;
    .otherText {
      display: flex;
      justify-content: space-between;
      font-size: 32px;
      font-weight: bold;
      color: #191f25;
      .deleteStyle {
        font-weight: 400;
        color: #ff4d4f
      }
    }
    .top {
      display: flex;
      justify-content: flex-start;
      padding-top: 10px;
      .icon {
        width: 6px;
        height: 32px;
        background: #1890ff;
        margin: 6px 10px 0 10px;
      }
      .title {
        width: 602px;
        margin-right: 20px;
        font-size: 30px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #191f25;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .titleWidth {
        width: 572px;
      }
    }
    .center {
      p {
        margin: 16px 25px;
        font-size: 28px;
        display: flex;
        position: relative;
        .key {
          color: #888888;
        }
        .value {
          color: #191f25;
          width: 380px;
          display: block;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .arrow {
          color: #1890ff;
          position: absolute;
          right: -10px;
        }
      }
      .showAll {
        background: #f5f8ff;
        width: 100vw;
        margin-left: -30px;
        padding: 30px;
        margin-bottom: 30px;
      }
      .showAll2 {
        width: 100%;
        margin: 0 0 30px 0;
        padding: 30px 0;
      }
    }

  }
}
</style>
